package com.jgzx.redis.login;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.jgzx.constant.CacheConstants;
import com.jgzx.constant.DataPermConstants;
import com.jgzx.constant.SymbolEnum;
import com.jgzx.domain.DataPermVO;
import com.jgzx.domain.LoginUser;
import com.jgzx.redis.config.RedisEnum;
import com.jgzx.redis.service.RedisService;
import com.jgzx.utils.AppContextUtil;
import com.jgzx.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author jackesy
 * @className: LoginCache
 * @description: 登录信息缓存
 * @create 2021/3/19 16:10
 **/

@Component
public class LoginCache {

    private static LoginCache loginCache;

    @Autowired
    private RedisService redisService;

    @PostConstruct
    public void init() {
        loginCache = this;
        loginCache.redisService = this.redisService;
    }

    /**
     * 获取登录缓存key
     * @return
     */
    public static String getTokenKey(String token){
        String[] strArr = StrUtil.split(token, ":");
        if (ArrayUtil.isEmpty(strArr) || strArr.length < 2) {
            return null;
        }
        String token_flag = strArr[0];
        String token_jwt = strArr[1];
        Long user_id = JwtUtil.getUserId(token_jwt);
        return CacheConstants.LOGIN_TOKEN_PREFIX_KEY + token_flag + ":" + user_id;
    }

    /**
     * 获取登录用户信息
     * @return
     */
    public static LoginUser getLoginUser(String token_key){
        String value = loginCache.redisService.get(RedisEnum.LOGIN_CACHE, token_key);
        if (StrUtil.isNotEmpty(value)) {
            LoginUser loginUser = JSON.parseObject(value, LoginUser.class);
            return loginUser;
        }
        return null;
    }

    /**
     * 获取登录用户信息
     * @return
     */
    public static LoginUser getLoginUser(){
        String token = AppContextUtil.getToken();
        String token_key = getTokenKey(token);
        LoginUser loginUser = getLoginUser(token_key);
        return loginUser;
    }

    /**
     * 获取PC端登录用户信息
     * @param user_id 用户ID
     */
    public static LoginUser getPlatformLoginUserById(Long user_id){
        if (ObjectUtil.isEmpty(user_id)) {
            return null;
        }
        String token_key = CacheConstants.LOGIN_TOKEN_PREFIX_KEY + CacheConstants.LOGIN_TOKEN_FLAG_PLATFORM + user_id;
        return getLoginUser(token_key);
    }

    /**
     * 获取PC端登录用户信息
     * @param user_id 用户ID
     */
    public static LoginUser getPcLoginUserById(Long user_id){
        if (ObjectUtil.isEmpty(user_id)) {
            return null;
        }
        String token_key = CacheConstants.LOGIN_TOKEN_PREFIX_KEY + CacheConstants.LOGIN_TOKEN_FLAG_PC_ENTERPRISE + user_id;
        return getLoginUser(token_key);
    }

    /**
     * 获取APP端登录用户信息
     * @param user_id 用户ID
     */
    public static LoginUser getAppLoginUserById(Long user_id){
        if (ObjectUtil.isEmpty(user_id)) {
            return null;
        }
        String token_key = CacheConstants.LOGIN_TOKEN_PREFIX_KEY + CacheConstants.LOGIN_TOKEN_FLAG_APP_ENTERPRISE + user_id;
        return getLoginUser(token_key);
    }

    /**
     * 通过数据权限构建数据条件SQL
     *  1.匹配到多个权限，使用最后一个
     * @param function_flag 功能标识
     * @param alias 别名
     * @return 数据权限过滤SQL
     */
    public static String getDataPermSql(String function_flag, String alias) {
        List<DataPermVO> dataPerms = LoginCache.getLoginUser().getDataPerm_list();
        DataPermVO dataPermVO = null;
        if (CollUtil.isNotEmpty(dataPerms)) {
            for (DataPermVO dataPerm : dataPerms) {
                if (ObjectUtil.equal(dataPerm.getFunction_flag(), function_flag)) {
                    dataPermVO = dataPerm;
                }
            }
        }
        StringBuilder dataPermSql = new StringBuilder();
        if (ObjectUtil.isNotNull(dataPermVO)) {
            String condition_value = dataPermVO.getCondition_value().replaceAll(DataPermConstants.ALIAS, alias)
                    .replaceAll(DataPermConstants.LOGIN_USER_ID, StrUtil.toString(AppContextUtil.getUserId()))
                    .replaceAll(DataPermConstants.LOGIN_ENTERPRISE_ID, StrUtil.toString(AppContextUtil.getEnterpriseId()));
            if (!SymbolEnum.SELF_SQL.value().equals(dataPermVO.getCondition_symbol())) {
                dataPermSql.append(" AND ");
                dataPermSql.append(alias);
                dataPermSql.append(".");
                dataPermSql.append(dataPermVO.getCondition_column());
                dataPermSql.append(dataPermVO.getCondition_symbol());
            }
            dataPermSql.append(" ");
            dataPermSql.append(condition_value);
        }
        return dataPermSql.toString();
    }
}
